<template>
  <!-- 考勤点列表 -->

  <el-dialog
    title="选择考勤点"
    v-model="visible"
    width="40%"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-table
      ref="table"
      row-key="id"
      stripe
      style="width: 100%"
      max-height="500"
      border
      :data="attendanceLocations"
      @selection-change="handleSelection"
    >
      <el-table-column type="selection" width="80" />
      <el-table-column
        label="考勤点名称"
        prop="pointsName"
        min-width="200"
      ></el-table-column>
      <el-table-column
        label="详细地址"
        prop="fullAddress"
        min-width="200"
      ></el-table-column>
    </el-table>

    <div class="addLocation">
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
        class="noFlex"
        v-if="showAddForm"
      >
        <el-form-item label="考勤点名称" prop="pointsName">
          <el-input
            v-model="form.pointsName"
            clearable
            placeholder="请输入考勤点名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="fullAddress">
          <el-input
            v-model="form.fullAddress"
            type="textarea"
            rows="3"
            clearable
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="有效范围(米)" prop="effectiveRange">
          <el-input
            v-model="form.effectiveRange"
            clearable
            placeholder="请输入有效范围"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="small"
        @click="showAddForm = true"
        v-if="!showAddForm"
        >添加考勤点</el-button
      >
      <el-button
        type="primary"
        size="small"
        @click="addLocation"
        class="addButtn"
        v-if="showAddForm"
        :loading="isAddSaveing"
        >添加</el-button
      >
    </div>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        v-if="mode != 'show'"
        type="primary"
        :loading="isSaveing"
        @click="confirmLocation"
        >确 定</el-button
      >
    </template>
  </el-dialog>
</template>
<script>
import loadBMap from '@/utils/loadBMap.js'
export default {
  data () {
    return {
      mode: "add",
      visible: false,
      isSaveing: false,
      isAddSaveing: false,
      showAddForm: false,
      //表单数据
      form: {
        pointsName: "",//考勤点名称
        fullAddress: "",//详细地址
        effectiveRange: '1000',//有效范围/米
        latitude: '',//纬度
        longitude: '',//纬度
      },
      attendanceLocations: [],//考勤点列表
      //验证规则
      rules: {
        pointsName: [
          { required: true, message: '请输入考勤点名称' }
        ],
        fullAddress: [
          { required: true, message: '请输入详细地址' }
        ],
        effectiveRange: [
          { required: true, message: '请输入有效范围' }
        ]
      },
      location: {},//定位经纬度
      selected: []
    }
  },
  async mounted () {
    await loadBMap()
    this.getAttendanceLocations()
  },
  methods: {
    //显示
    open (list) {
      this.visible = true
      this.showSelected(list)
      return this
    },

    // 获取考勤点列表
    async getAttendanceLocations () {
      let res = await this.$API.attendance.getAttendanceLocations.get()
      this.attendanceLocations = res.data
    },

    // 选考勤点
    handleSelection (val) {
      this.selected = val
    },
    //添加考勤点
    async addLocation () {
      this.location = await this.getPointByAddress()
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.isAddSaveing = true
          // this.form.latitude = this.location.lat
          // this.form.longitude = this.location.lng
          let lat = this.location.lat.toFixed(6)
          let lng = this.location.lng.toFixed(6)
          this.form.latitude = parseFloat(lat)
          this.form.longitude = parseFloat(lng)
          let res = null
          if (this.mode == 'add') {
            res = await this.$API.attendance.addAttendanceLocation.post(this.form)
          }
          this.isAddSaveing = false
          if (res.code == 200) {
            this.getAttendanceLocations()
            this.$refs.addForm.resetFields()
            this.$message.success("操作成功")
          }
        }
      })
    },

    // 确定
    confirmLocation () {
      this.visible = false
      this.$emit('showLocation', this.selected)
    },

    // 编辑班次时回显已选人员
    showSelected (list) {
      this.selected = []
      list.forEach(item => {
        this.attendanceLocations.forEach((a_item, index) => {
          if (item == a_item.pointsName) {
            this.selected.push(a_item)
            this.$nextTick(() => {
              this.$refs.table.toggleRowSelection(this.attendanceLocations[index], true)
            })
          }
        })
      })

    },

    // 根据地址获取经纬度
    getPointByAddress () {
      // 创建地理编码实例
      // eslint-disable-next-line no-undef
      const myGeo = new BMap.Geocoder()
      return new Promise((resolve, reject) => {
        // 对地址进行地理编码
        myGeo.getPoint(this.form.fullAddress, (point) => {
          if (point) {
            // 地理编码成功，返回经纬度坐标对象
            console.log(point)
            resolve(point)
          } else {
            // 地理编码失败
            // this.$message.error("考勤点定位失败，请确认地址重新定位")
            reject('考勤点定位失败，请确认地址重新定位')

          }
        }, '全国')
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.addLocation {
  margin-top: 30px;
  .el-button {
    margin-bottom: 30px;
  }
  .addButtn {
    margin-left: 100px;
  }
}
</style>